package com.zbkj.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.admin.service.SafeDeptService;
import com.zbkj.common.model.safe.SafeDept;
import com.zbkj.service.dao.safe.SafeDeptDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.guqianbin
 * @description SafeDeptServiceImpl 接口实现
 * @date 2022-11-11
 */
@Service
public class SafeDeptServiceImpl extends ServiceImpl<SafeDeptDao, SafeDept> implements SafeDeptService {

    @Resource
    private SafeDeptDao dao;


    @Override
    public void syncDept(JSONObject jsonObject) {
        SafeDept safeDept = JSONObject.parseObject(jsonObject.toJSONString(), SafeDept.class);
        SafeDept mysqlDept = getById(safeDept.getId());
        if (ObjectUtil.isEmpty(mysqlDept)) {
            save(safeDept);
        }
        JSONArray childDepts = jsonObject.getJSONArray("children");
        if (CollectionUtil.isNotEmpty(childDepts)) {
            for (int i = 0; i < childDepts.size(); i++) {
                syncDept(childDepts.getJSONObject(i));
            }
        }
    }

    public List<SafeDept> getChildrenDeptTree(String cityCode) {
        String id=comparePid(cityCode);
        SafeDept safeDept=getById(id);
        List<SafeDept> childrenDept= getDeptTree(safeDept);
        safeDept.setChildren(childrenDept);

        List<SafeDept> safeDepts=new ArrayList<>();
        safeDepts.add(safeDept);
        return  safeDepts;
    }

    @Override
    public List<SafeDept> getAreaDeptTree(String cityCode) {
        return null;
    }

    private List<SafeDept> getDeptTree(SafeDept dept) {
        List<SafeDept> safeDepts = new ArrayList<>();
        if (dept.getLeaf()) {
            return safeDepts;
        }
        LambdaQueryWrapper<SafeDept> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SafeDept::getPid, comparePid(dept.getExtend02()));
        safeDepts = list(lqw);
        safeDepts.forEach(safeDept -> {
           safeDept.setChildren(getDeptTree(safeDept));
        });
        return safeDepts;
    }


    @Override
    public String comparePid(String cityCode) {
        int length = cityCode.length();
        StringBuilder stringBuilder = new StringBuilder(cityCode);
        while (length < 19) {
            stringBuilder.append("0");
            length++;
        }
        return stringBuilder.toString();
    }

    @Override
    public SafeDept getParent(String cityCode) {
        String id=comparePid(cityCode);
        SafeDept dept=getById(id);
        String pid=dept.getPid();
        SafeDept pDept=getById(pid);
        return pDept;
    }


}

